package com.zhai.trigger.job;

import com.zhai.domain.activity.model.valobj.ActivitySkuStockKeyVO;
import com.zhai.domain.activity.service.IRaffleActivitySkuStockService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @Description: 更新活动sku库存
 * @ClassName: UpdateActivitySkuStockJob
 * @Author: zhaiyongxin
 * @Date: 2025/2/24 17:24
 * @Version: 1.0
 */
@Component()
@Slf4j
public class UpdateActivitySkuStockJob {

    @Resource
    private IRaffleActivitySkuStockService skuStock;
    @Resource
    private ThreadPoolExecutor executor;


    @Scheduled(cron = "0/5 * * * * ?")
    public void exec(){
        try {
            //log.info("定时任务，更新活动sku库存【延迟队列获取，降低对数据库的更新频次，不要产生竞争】");
            List<Long> skuStockList = skuStock.querySkuStockList();
            for (Long sku : skuStockList) {
                executor.execute(() -> {
                    ActivitySkuStockKeyVO activitySkuStockKeyVO = null;
                    try {
                        activitySkuStockKeyVO = skuStock.takeQueueValue(sku);
                        if (activitySkuStockKeyVO == null) return;
                        log.info("定时任务，更新活动sku库存 sku:{} activityId:{}", activitySkuStockKeyVO.getSku(), activitySkuStockKeyVO.getActivityId());
                        skuStock.updateActivitySkuStock(activitySkuStockKeyVO);
                    } catch (Exception e) {
                        log.error("定时任务，更新活动sku库存失败 sku:{} activityId:{}", activitySkuStockKeyVO.getSku(), activitySkuStockKeyVO.getActivityId(), e);
                    }
                });
            }
        } catch (Exception e) {
            log.error("定时任务，更新活动sku库存失败", e);
        }
    }
}
